import os
import sys
import numpy as np

from PIL import Image
from pathlib import Path


if __name__ == "__main__":

    STEP_VIDEO_CONVERT_25FPS = True
    STEP_VIDEO_EXTRACT_FRAME = True
    STEP_VIDEO_EXTRACT_3DMM = False

    STEP_AUDIO_TO_EXPRESSION = False

    STEP_CHOOSE_BG = False
    STEP_RENDER = False


    path_data = Path("../data")

    path_audio = path_data.joinpath('audio/input/03Fsi1201.wav')
    path_video = path_data.joinpath('video/input/ken.mp4')
    path_video_fps = path_data.joinpath('tmp/video/ken-25fps-720p.mp4')


    path_save = path_data.joinpath('tmp')
    path_save_audio = path_data.joinpath('tmp/audio')
    path_save_video = path_data.joinpath('tmp/video')

    # video_name = path_video_fps.stem

    ### convert the target video to 25fps
    if STEP_VIDEO_CONVERT_25FPS:
        cmd = f"cd video; "\
              f"ffmpeg  -loglevel error -i {path_video} -r 25 tmp.mp4; "
        print(f"[xxxx] RUN: \n [xxxx] {cmd}")
        os.system(cmd)

        cmd = f"cd video; "\
              f"ffmpeg -loglevel error -i tmp.mp4 -vf scale=\"720:-1\" {path_video_fps}"
        print(f"[xxxx] RUN: \n [xxxx] {cmd}")
        os.system(cmd)

    ### extract frames and landmarks by
    #path_video_fps = path_data.joinpath('video/input/31.mp4')
    if STEP_VIDEO_EXTRACT_FRAME:
        cmd = f"cd video; "\
            f"python utils/extract_frames.py --path_video {path_video_fps} --path_save {path_save_video}"

        print(f"[xxxx] RUN: \n [xxxx] {cmd}")
        os.system(cmd)

    ### extract 3DMM coeffs per frames
    if STEP_VIDEO_EXTRACT_3DMM:
        cmd = f"cd reconstruction;"\
              f"CUDA_VISIBLE_DEVICES=0 python reconstruct.py --path_video {path_video_fps} --path_save {path_save_video}"

        print(f"[xxxx] RUN: \n [xxxx] {cmd}")
        os.system(cmd)

    ### Audio-to-Expression
    if STEP_AUDIO_TO_EXPRESSION:
        cmd = f"cd audio;" \
            f"python inference.py --path_input {path_audio} --path_save {path_save_audio}"

        print(f"[xxxxx] RUN: \n[xxxxx] {cmd}")
        os.system(cmd)

    ### Background matching
    if STEP_CHOOSE_BG:
        pass

    ### Render to 3DMM
    if STEP_RENDER:
        cmd = f"cd reconstruction; \
                CUDA_VISIBLE_DEVICES=0; \
                python render.py --path_video {path_video_fps} --path_audio {path_audio} --path_save {path_save}"

        print(f"[xxxxx] RUN: \n[xxxxx] {cmd}")
        os.system(cmd)

